package com.example.activity.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@Slf4j
public class FileUploadUtil {

    /**
     * 获取文件相对路径：年/月/日/时分秒
     *
     * @return 文件相对路径
     */
    public static String getUploadPath() {
        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int monthValue = now.getMonthValue();
        int dayOfMonth = now.getDayOfMonth();

        LocalTime localTime = now.toLocalTime();
        String HHmmss = localTime.format(DateTimeFormatter.ofPattern("HHmmss"));

        return year + File.separator
                + monthValue + File.separator
                + dayOfMonth + File.separator
                + HHmmss;
    }

    /**
     * 获取文件类型
     *
     * @param fileName 文件名称
     * @return 文件类型
     */
    public static String getFileType(String fileName) {
        if (StrUtil.isBlank(fileName)) {
            return null;
        }
        int lastIndexOf = fileName.lastIndexOf(".");
        if (lastIndexOf == -1) {
            // 不存在
            return null;
        }

        return fileName.substring(lastIndexOf + 1);
    }

    /**
     * 关闭流
     * @param inputStreamList 输入流列表
     */
    public static void closeStream(InputStream... inputStreamList) {
        if (inputStreamList == null) {
            return;
        }

        for (InputStream inputStream : inputStreamList) {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                log.error("关闭流异常", e);
            }
        }

    }

    public static void main(String[] args) {
        String uploadPath = getUploadPath();
        System.out.println(uploadPath);
    }
}
